"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""

import requests
from flask import Blueprint, jsonify, request


from sqlalchemy.orm import sessionmaker

from model.sqlalchemy_base import TestCase, engine
from utils.log_util import logger

testcase_bp = Blueprint('testcase', __name__, url_prefix='/zijie/testcase')


@testcase_bp.route('/add', methods=['POST'])
def add():

    try:
        # 解析请求消息request
        req_data = request.json
        print(req_data)
        logger.info(f'请求数据===>{req_data}')

        # 创建模型对象Model
        new_case = TestCase(
            name=req_data.get('name'),
            url=req_data.get('url'),
            method=req_data.get('method'),
            params=req_data.get('params'),
            data=req_data.get('data')
        )

        # 写入数据库orm
        db_session = sessionmaker(bind=engine)()
        db_session.add(new_case)

        db_session.commit()
        db_session.close()

        resp = {
            "code": 0,
            "msg": "新增成功！"
        }

    except Exception as e:
        resp = {
            "code": -1,
            "msg": f"新增失败，原因：{e}"
        }
        logger.warning(f'{e}')

    # 返回响应消息
    return jsonify(resp)


@testcase_bp.route('/list', methods=['GET'])
def list():

    try:
        # 查询表记录
        db_session = sessionmaker(bind=engine)()
        cases = db_session.query(TestCase).all()
        logger.info(cases)

        cases_list = [case.as_dict() for case in cases]

        resp = {
            "code": 0,
            "msg": "查询成功！",
            "data": cases_list
        }

        db_session.commit()
        db_session.close()

    except Exception as e:
        resp = {
            "code": -1,
            "msg": f"查询失败，原因：{e}"
        }

    return jsonify(resp)


@testcase_bp.route('/update', methods=['POST'])
def update():
    resp = {
        "code": 0,
        "msg": "更新成功！",
        "data": []
    }

    try:

        # 解析请求数据
        req_data = request.json

        # 查询对象
        case_id = req_data.get('id')
        db_session = sessionmaker(bind=engine)()
        case = db_session.query(TestCase).filter_by(id=case_id).first()

        # 修改模型对象
        case.name = req_data.get('name')
        case.url = req_data.get('url')
        case.method = req_data.get('method')
        case.params = req_data.get('params')
        case.data = req_data.get('data')

        # 提交事务
        db_session.commit()
        db_session.close()

    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"更新失败，原因：{e}"
        }

    return jsonify(resp)


@testcase_bp.route('/delete', methods=['POST'])
def delete():


    try:
        # 解析请求数据
        req_data = request.args
        case_id = req_data.get('id')

        # 查询模型对象
        db_session = sessionmaker(bind=engine)()
        case = db_session.query(TestCase).filter_by(id=case_id).first()

        # 删除
        db_session.delete(case)

        db_session.commit()
        db_session.close()

        resp = {
            "code": 0,
            "msg": "删除成功！"
        }
    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"删除失败，原因：{e}"
        }

    return jsonify(resp)


@testcase_bp.route('/debug', methods=['POST'])
def debug():


    try:

        # 解析请求数据
        req_data = request.args
        case_id = req_data.get('id')

        # 查询记录
        db_session = sessionmaker(bind=engine)()
        case = db_session.query(TestCase).filter_by(id=case_id).first()

        # 发送请求requests
        case_dict: dict = case.as_dict()
        print(case_dict.get('data'))
        case_dict.pop('name')
        case_dict.pop('id')
        r = requests.request(**case_dict)
        if r.status_code == 200:
            resp = {
                "code": 0,
                "msg": "调试成功！"
            }
        else:
            resp = {
                "code": -1,
                "msg": f"调试失败，响应状态码为：{r.status_code}"
            }
    except Exception as e:
        logger.warning(e)
        resp = {
            "code": -1,
            "msg": f"调试失败，原因：{e}"
        }

    return jsonify(resp)
